﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web;
using System.IO;
using Ricciolo.StylesExplorer.Model;

namespace Ricciolo.StylesExplorer.Forms
{
    public partial class HandleErrorDialog : Ricciolo.StylesExplorer.Forms.BaseDialog
    {

        private const string ErrorReportUri = "http://ricciolo.lab.aspitalia.com/StylesExplorer/Report.aspx";
        private Exception exception;

        public HandleErrorDialog(Exception e)
        {
            this.exception = e;
            InitializeComponent();

            this.errorMessage.Text = e.ToString();
            this.includeResource.Enabled = (e is DecompilingXamlException);
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string uri = String.Format("{0}?message={1}", ErrorReportUri, HttpUtility.UrlEncode(errorMessage.Text));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = WebRequestMethods.Http.Post;

            if (this.exception is DecompilingXamlException && this.includeResource.Checked)
            {
                byte[] data = ((DecompilingXamlException)this.exception).BamlData;
                if (data.Length > 0)
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted)
                throw new HttpException((int)response.StatusCode, response.StatusDescription);
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
                this.DialogResult = DialogResult.OK;
            else
            {
                if (MessageBox.Show(this, e.Error.Message, Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Retry)
                    this.backgroundWorker.RunWorkerAsync();
                else
                    this.DialogResult = DialogResult.Cancel;
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (this.backgroundWorker.IsBusy)
                this.backgroundWorker.CancelAsync();

            this.DialogResult = DialogResult.Cancel;
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            this.sendButton.Enabled = false;
            this.backgroundWorker.RunWorkerAsync();
        }
    }
}
